﻿using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using LitJson;

public class UDPClient : MonoBehaviour
{
    public string recvStr;
    public string IP = "127.0.0.1";
    public int Prot = 7401;
    Socket socket;
    EndPoint serverEnd;
    IPEndPoint ipEnd;

    byte[] recvData = new byte[100];
    byte[] data = new byte[100];
    int SendNum = 0;
    int recvLen = 0;
    Thread connectThread;

    void Start()
    {
        IP = IP.Trim();
        InitSocket();
        //JsonData jsonD = GeJSON.LoadJson("Data/Event.json", (d) => { });
        //GeJSON.SaveJson("Data/Event2.json", jsonD);
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.J))
        {
            SendNum++;
            string msg = "pos" + SendNum.ToString();
            Send(msg);
            //Debug.Log(msg);
        }
    }

    void InitSocket()
    {
        ipEnd = new IPEndPoint(IPAddress.Parse(IP), Prot);
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        serverEnd = (EndPoint)sender;
        print("开启UDP连接" + ipEnd);
        Send("客户端01发送消息");
        //开启一个线程连接
        connectThread = new Thread(new ThreadStart(Receive));
        connectThread.Start();
    }
    void Send(string msg)
    {
        //清空
        data = new byte[100];
        //数据转换
        data = Encoding.UTF8.GetBytes(msg);
        //发送给指定服务端
        int end = socket.SendTo(data, data.Length, SocketFlags.None, ipEnd);
        Debug.Log("客户端发送消息:" + msg + end);
    }

    //接收服务器信息
    void Receive()
    {
        while (true)
        {

            recvData = new byte[100];
            try
            {
                recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
            }
            catch (Exception e)
            {
            }

            print("信息来自: " + serverEnd.ToString());
            if (recvLen > 0)
            {
                recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
            }

            print(recvStr);
        }
    }

    //连接关闭
    void SocketQuit()
    {
        //关闭线程
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (socket != null)
            socket.Close();
    }
    void OnApplicationQuit()
    {
        SocketQuit();
    }
}
